<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> 
	<!--[if IE]><meta http-equiv="refresh" content="0;URL=chat.php"/><![endif]-->
	<title>Chat</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
	<script type="text/javascript" src="http://jqueryjs.googlecode.com/svn/trunk/plugins/color/jquery.color.js"></script>
	<script type="text/javascript">//<![CDATA[
		var alt = true,
			focused = true,
			newMessages = 0,
			name = '',
			room = 'public',
			updateRequest,
			onlineRequest,
			timeDiff = 0;

		if (!location.hash)
			location.hash = room;
		room = location.hash.substr(1).toLowerCase().replace(/[^a-z0-9\-_]/g, '');

		document.title = 'Chat (' + room + ')';

		$.getScript('name.php');

		$(window).focus(function(){
			focused = true;
			newMessages = 0;
			document.title = 'Chat (' + room + ')';
		}).blur(function(){
			focused = false;
		});

		$.get(
			'curtime.php',
			{},
			function(serverTime){
				timeDiff = Math.round(serverTime - new Date / 1000);
			},
			'text'
		);

		setInterval(function(){
			if (document.title == 'Chat (' + room + ')' && room != location.hash.substr(1)) {
				room = location.hash.substr(1).toLowerCase().replace(/[^a-z0-9\-_]/g, '');
				if (room != location.hash.substr(1))
					location.hash = room;
				document.title = 'Chat (' + room + ')';
				$('h1').text(document.title = 'Chat (' + room + ')');
				$('#online img').remove();
				$('#chat div').hide('slow', function(){
					$(this).remove();
				});
				update();
				updateOnline(true);
				updateChannels();
			}
		}, 50);

		setInterval(function(){
			if (newMessages) {
				switch (document.title) {
					case 'Chat (' + room + ', ' + newMessages + ' new)':
						document.title = '* Chat (' + room + ', ' + newMessages + ' new) *';
						break;
					case '* Chat (' + room + ', ' + newMessages + ' new) *':
						document.title = '** Chat (' + room + ', ' + newMessages + ' new) **';
						break;
					case '** Chat (' + room + ', ' + newMessages + ' new) **':
						document.title = '*** Chat (' + room + ', ' + newMessages + ' new) ***';
						break;
					case '*** Chat (' + room + ', ' + newMessages + ' new) ***':
						document.title = 'Chat (' + room + ', ' + newMessages + ' new)';
						break;
				}
			}
		}, 600);

		$.ajaxSetup({
			timeout: 500000
		});

		function updateTime(element) {
			function time_since(date) {
					function plural(num) {
						if (num != 1)
							return 's';
						return '';
					}
					function numberSuffix(d) {
						d = d + '';
						return d.substr(-Math.min(d.length, 2)) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(+d % 10, 4)];
					}
				var diff = Math.floor(new Date / 1000) - date + timeDiff, _date = new Date(date);
				if (diff == 0)
					return 'Right now';
				if (diff < 60)
					return diff + ' second' + plural(diff) + ' ago';
				diff = Math.floor(diff / 60);
				if (diff < 60)
					return diff + ' minute' + plural(diff) + ' ago';
				diff = Math.floor( diff / 60 );
				if (diff < 24)
					return diff + ' hour' + plural(diff) + ' ago';
				diff = Math.floor(diff / 24);
				if (diff < 7)
					return diff + ' day' + plural(diff) + ' ago';
				diff = Math.floor(diff / 7);
				if (diff < 4)
					return diff + ' week' + plural(diff) + ' ago';
				return 'on ' + _date.toLocaleFormat('%B %e<sup>' + numberSuffix(_date.getDate()) + '</sup>, %Y');
			}

			$(element).html(time_since($(element).data('time')));
			return element;
		}

		function updateAllTime() {
			$('.time').each(function(){
				updateTime(this);
			});
		}
		setInterval(updateAllTime, 500);

		function update(start) {
			try {
				if (updateRequest)
					updateRequest.abort();
			} catch (ex) {}
			updateRequest = $.get(
				'get.php',
				{ pos: +start, room: room },
				function(abc){
					var messages = abc.split('\n');
					updateRequest = null;
					update(messages[messages.length - 1]);
					delete messages[messages.length - 1];
					messages = $.grep(messages, function(a){
						return a;
					});
					$.each(messages, function(i){
						setTimeout(function(a){
							if (!focused) {
								newMessages++;
								document.title = 'Chat (' + room + ', ' + newMessages + ' new)';
							}
							$('<div/>').addClass('chat-from-' + a.substr(0, 32) + ( alt ? ' alt' : '' )).css({
								backgroundColor: alt ? '#fff' : '#f7f7f7',
								fontFamily: 'sans-serif',
								fontSize: a.indexOf(':Global:') != -1 ? '1.25em' : '1em',
								width: '75%'
							}).text(' ' + decodeURIComponent(a.split(':').slice(2).join(':').replace(/\+/g, ' '))).each(function(){
								$(this).html($(this).html().replace(/(^|\s)#([a-zA-Z0-9\-_]+)/g, '$1#<a style="color: #00f" href="#$2">$2</a>'));
								$(this).html($(this).html().replace(/(ht|f)tps?:\/\/((\w+)(:(\w+))?@)?([a-zA-Z0-9\-.]+|\[[a-zA-Z0-9\-.]+\])\.?(:(\d+))?(\/\S*)?/g, function(a){
									return '<a style="color: #11c" target="_blank" href="' + $('<div/>').html(a).text() + '">' + a + '</a>';
								}));
							}).prepend($('<strong/>').text(' ' + decodeURIComponent(a.substr(32).split(':')[0].replace(/\+/g, ' ')) + ':')).prepend($('<img/>').attr({
								src: 'http://gravatar.com/avatar/' + a.substr(0, 32) + '?d=identicon&s=15&r=d',
								width: 15,
								height: 15
							})).prepend(updateTime($('<span class="time"/>').css({
								fontSize: 'smaller',
								cssFloat: 'right',
								display: 'block',
								margin: 2
							}).data('time', a.split(':')[1]))).hide().appendTo('#chat').show('normal');
							if ($('#chat div').length > 25)
								$($('#chat div').get().reverse().slice(25)).hide('slow', function(){
									$(this).remove();
								});
							alt = !alt;
						}, +start > 0 ? i * 500 : 0, this);
					});
				}, 'text'
			);
		}
		function updateOnline(immediate) {
			try {
				if (onlineRequest)
					onlineRequest.abort();
			} catch (ex) {}
			onlineRequest = $.get(
				'online.php',
				immediate === true ? { immediate: 1, room: room } : { room: room },
				function(abc){
					var users = abc.split('\n');
					$('#online img').remove();
					$.each(users, function(){
						var id = this.substr(0, 32);
						$('<img/>').attr({
							src: 'http://gravatar.com/avatar/' + id + '?d=identicon&s=48&r=d',
							width: 48,
							height: 48,
							title: decodeURIComponent(this.substr(this.indexOf(':') + 1).replace(/\+/g, ' ')),
							alt: decodeURIComponent(this.substr(this.indexOf(':') + 1).replace(/\+/g, ' '))
						}).hover(function(){
							$('.alt.chat-from-' + id).stop().animate({
								backgroundColor: '#ffb'
							}, 'normal');
							$('.chat-from-' + id + ':not(.alt)').stop().animate({
								backgroundColor: '#f7f7bb'
							}, 'normal');
						}, function(){
							$('.alt.chat-from-' + id).stop().animate({
								backgroundColor: '#fff'
							}, 'normal');
							$('.chat-from-' + id + ':not(.alt)').stop().animate({
								backgroundColor: '#f7f7f7'
							}, 'normal');
						}).appendTo('#online');
					});
					onlineRequest = null;
					updateOnline();
				},
				'text'
			);
		}
		function updateChannels() {
			$.get(
				'channels.php',
				{},
				function(data){
					$('#channels tbody tr').remove();
					var alt = false, channels = data.split(/\n/g);
					$.each(channels, function(){
						var channel = this.split(/:/g);
						if (channel[0] == room)
							return;
						$('<tr/>').css({
							backgroundColor: alt ? '#f7f7f7' : '#fff',
							color: '#333'
						}).hover(function(){
							$(this).stop().animate({
								color: '#000'
							}, 'fast').find('a').stop().animate({
								color: '#00f'
							}, 'fast');
						}, function(){
							$(this).stop().animate({
								color: '#333'
							}, 'fast').find('a').stop().animate({
								color: '#33f'
							}, 'fast');
						}).append($('<th/>').attr({scope: 'row'}).css({textAlign: 'left'}).text('#').append($('<a/>').text(channel[0]).attr({href: '#' + channel[0]}).css({color: '#33f'}))).append($('<td/>').html(channel[1])).append($('<td/>').text(channel[2])).append($('<td/>').html(channel[3])).find('th, td').css({border: '1px solid #ccc'}).end().appendTo('#channels tbody');
						alt = !alt;
					});
				},
				'text'
			);
		}
		setInterval(updateChannels, 15000);

		$(function(){
			$('h1').text(document.title = 'Chat (' + room + ')');
			update();
			updateOnline(true);
			updateChannels();
			$('input').css({
				width: '100%'
			});
			$('#right').css({
				width: '25%',
				cssFloat: 'right',
				clear: 'right',
				fontFamily: 'sans-serif'
			});
			$('#online').add('#channels').find('table').css({
				width: '100%',
				outline: '1px solid #333',
				borderCollapse: 'collapse'
			}).find('th').css({
				backgroundColor: '#555',
				color: '#fff',
				border: '1px solid #ddd'
			}).end().end().end().find('h2').css({
				marginTop: 0
			}).add('h1,h2').css({
				fontFamily: 'Impact, sans-serif',
				fontWeight: 'normal'
			});
			$('form').submit(function(){
				if ( $.trim($('input').val()).length )
					$.get(
						'send.php',
						{ message: $('input').val(), room: room }
					);
				$('input').val('');
				return false;
			});
		});
		var wot_rating_options = {
			updateinterval: 1000
		};
//]]></script>
	<script type="text/javascript" src="http://api.mywot.com/widgets/ratings.js"></script>
</head>
<body>
	<div id="right">
		<div id="online"><h2>Users online</h2></div>
		<div id="channels"><h2>Other channels</h2><table><thead><tr><th scope="col">Name</th><th scope="col">Last message</th><th scope="col">Last viewed</th><th scope="col">Users</th></tr></thead><tbody></tbody></table></div>
	</div>
	<h1>Chat</h1>
	<div id="chat"></div>
	<form><input type="text"/></form>
	<noscript><meta http-equiv="refresh" content="0;URL=chat.php"/></noscript>
</body>
</html>